package com._101aiot.auth.controller;

import com._101aiot.auth.api.AuthToken;
import com._101aiot.auth.exception.ResponseEnum;
import com._101aiot.auth.service.impl.AuthServiceImpl;
import com._101aiot.common.resultutil.CommonResult;
import com._101aiot.common.util.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;


/**
 * 统一鉴权控制器
 */
@RestController
@RequestMapping("/")
public class AuthController {

    @Value("${auth.clientId}")
    String clientId;

    @Value("${auth.clientSecret}")
    String clientSecret;

    @Value("${auth.cookieDomain}")
    String cookieDomain;

    @Value("${auth.cookieMaxAge}")
    int cookieMaxAge;

    @Autowired
    AuthServiceImpl authService;

    @PostMapping("/user/login")
    public CommonResult<?> login(String username, String password) {

        ResponseEnum.AUTH_USERNAME_NONE.textNotEmpty(username);


        ResponseEnum.AUTH_PASSWORD_NONE.textNotEmpty(password);
        // 用户名称为空
//        if (StrUtil.isEmpty(username)) {
//            ExceptionCast.cast(ResultCode.AUTH_USERNAME_NONE);
//
//        }

        // 密码错误：提示用户名密码不存在
//        if (StrUtil.isEmpty(password)) {
//            ResponseEnum.AUTH_PASSWORD_NONE.assertError();
//            ExceptionCast.cast(ResultCode.AUTH_PASSWORD_NONE);
//        }

        // 申请令牌
        AuthToken authToken = authService.login(username, password, clientId, clientSecret);

        // 用户身份令牌
        String accessToken = authToken.getAccessToken();
        // 将令牌写入到浏览器Cookie
        this.saveCookie(accessToken);

        return CommonResult.success(accessToken);
    }

    /**
     * 将令牌存储到cookie
     *
     * @param token token
     */
    private void saveCookie(String token) {

        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        //HttpServletResponse response,String domain,String path, String name, String value, int maxAge,boolean httpOnly
        CookieUtil.addCookie(response, cookieDomain, "/", "uid", token, cookieMaxAge, false);
    }

    /**
     * 退出登录
     * 1. 清楚redis等令牌，
     * 2. 清除登录的Cookie
     *
     * @return CommonResult
     */
    public CommonResult<?> logout() {

        return null;
    }
}
